<template>
  <el-upload class="avatar-uploader" ref="img" action="/api/file/upload" :show-file-list="false"
    :on-success="handleImgUploadSuccess">
    <img v-if="imageUrl" :src="imageUrl" class="avatar">
    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
  </el-upload>
</template>

<script>
export default {
  name: "ImageUpload",
  props: {
    // 图片URL，可以是一个prop，外部传入
    value: {
      type: String,
      default: ''
    }
  },
  computed: {
    imageUrl: {
      get() {
        return this.value;
      },
      set(newVal) {
        this.$emit('input', newVal);
      }
    }
  },
  methods: {
    // 图片上传成功的回调
    handleImgUploadSuccess(res) {
      this.imageUrl = res;
      this.$emit('upload-success', res);
    },
    // 清除文件
    clearFiles() {
      if (this.$refs.img) {
        this.$refs.img.clearFiles();
      }
      this.imageUrl = '';
    }
  }
}
</script>

<style>
.avatar-uploader {
  padding-left: 20px;
  padding-bottom: 10px;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 138px;
  height: 138px;
  line-height: 138px;
  text-align: center;
}

.avatar {
  width: 138px;
  height: 138px;
  display: block;
}
</style>